package com.novunda.platform.web;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.novunda.platform.common.utils.StringUtil;
import com.novunda.platform.common.web.controller.BaseController;
import com.novunda.platform.entities.Menu;
import com.novunda.platform.entities.Role;
import com.novunda.platform.entities.User;
import com.novunda.platform.services.PlatformService;
import com.novunda.platform.web.model.ResultModel;
import com.novunda.platform.web.model.UserInfo;

/**
 * .
 * 功能说明：查询用户
 * @author FJ
 * @see 2016年9月20日
 * @version 1.0
 */
@Controller
@RequestMapping("/query/user")
public class UserQueryController extends BaseController {
	
	@Autowired
	private PlatformService platformService;

	/**
	 * .
	 *功能说明：根据账号名获取帐号
	 * @param username 账号名
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getUserInfoByName", produces = "application/json;charset=utf-8")
	public ResultModel<UserInfo> getUserInfoByName (String username) {
		ResultModel<UserInfo> model = new ResultModel<UserInfo>();
		try {
			User user = platformService.getUserByLoginName(username);
			if (null == user) {
				model.setReturnCode(-1);
				model.setReturnMessage("the user " + username +" doesn't exist");
				return model;
			}
			UserInfo userInfo = new UserInfo();
			userInfo.setCreatename(user.getCreateBy().getLoginName());
			userInfo.setCreatetime(user.getCreateDate());
			userInfo.setEmail(user.getEmail());
			userInfo.setId(user.getId());
			userInfo.setMobilephone(user.getMobile());
			userInfo.setOrg(user.getCompany().getName());
			userInfo.setOffice(user.getOffice().getName());
			userInfo.setPassword(user.getPassword());
			userInfo.setRealname(user.getRealName());
			userInfo.setState(user.getState());
			userInfo.setUsername(user.getLoginName());
			List<String> userRoles = new ArrayList<String>();
			List<String> permissions = new ArrayList<String>();
			List<Role> roles = user.getRoleList();
			for (Role role : roles) {
				userRoles.add(role.getName());
				List<Menu> menus = role.getMenuList();
				for (Menu menu : menus) {
					String permission = menu.getPermission();
					if (!StringUtil.isEmpty(permission)) {
						permissions.add(menu.getPermission());
					}
				}
			}
			userInfo.setUserRoles(userRoles);
			userInfo.setPermissions(permissions);
			model.setObject(userInfo);
		} catch(Exception e) {
			LOG.error(e.getMessage(), e);
			model.setReturnCode(1);
			model.setReturnMessage("query is inner exception");
		}
		return model;
	}

}
